<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户" prop="userId">
        <id-selector
          v-model="queryParams.userId"
          placeholder="请选择用户"
          dialog-title="选择用户"
          :api-function="listUser"
          :get-api-function="getUser"
          id-field="userId"
          name-field="userName"
          id-label="用户ID"
          name-label="用户名称"
          search-label="用户名称"
          search-placeholder="请输入用户名称"
          :extra-columns="[{prop: 'nickName', label: '用户昵称'}, {prop: 'email', label: '邮箱'}]"
        />
      </el-form-item>
      <el-form-item label="商品" prop="productId">
        <id-selector
          v-model="queryParams.productId"
          placeholder="请选择商品"
          dialog-title="选择商品"
          :api-function="listProduct"
          :get-api-function="getProduct"
          id-field="productId"
          name-field="productName"
          id-label="商品ID"
          name-label="商品名称"
          search-label="商品名称"
          search-placeholder="请输入商品名称"
          :extra-columns="[{prop: 'productCode', label: '商品编码'}, {prop: 'price', label: '价格'}]"
        />
      </el-form-item>
      <el-form-item label="浏览时间" prop="browseTime">
        <el-date-picker clearable
          v-model="queryParams.browseTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择浏览时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- 删除按钮已删除 -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:browseHistory:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="historyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户" align="center" prop="userName" width="120" />
      <el-table-column label="创建组织" align="center" width="120">
        <template slot-scope="scope">
          <span>{{ getDeptName(scope.row.orgId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品" align="center" width="150" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ getProductNameById(scope.row.productId) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="商品价格" align="center" prop="productPrice" />
      <el-table-column label="浏览时间" align="center" prop="browseTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.browseTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="浏览时长(秒)" align="center" prop="browseDuration" />
      <el-table-column label="设备类型(mobile/pc)" align="center" prop="deviceType" />
      <el-table-column label="IP地址" align="center" prop="ipAddress" />
      <!-- 操作列已隐藏 -->
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:browseHistory:remove']"
          >删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


  </div>
</template>

<script>
import { listHistory, delHistory } from "@/api/system/history"
import { getDept } from "@/api/system/dept"
import { listUser, getUser } from "@/api/system/user"
import { listProduct, getProduct } from "@/api/fun/product"
import IdSelector from '@/components/IdSelector'
import CacheManager from '@/utils/cacheManager'

export default {
  name: "History",
  components: {
    IdSelector
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户浏览足迹表格数据
      historyList: [],
      // API方法
      listUser,
      listProduct,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        productId: null,
        browseTime: null,
      },

    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 根据部门ID获取部门名称 */
    getDeptName(deptId) {
      return CacheManager.getDeptName(deptId, getDept)
    },
    /** 查询用户浏览足迹列表 */
    getList() {
      this.loading = true
      listHistory(this.queryParams).then(response => {
        this.historyList = response.rows
        this.total = response.total
        // 首次加载时预取关联名称，避免显示“加载中...”
        try {
          const deptItems = []
          const productItems = []
          const seenDept = new Set()
          const seenProduct = new Set()
          (this.historyList || []).forEach(row => {
            if (row.orgId && !seenDept.has(row.orgId)) {
              seenDept.add(row.orgId)
              deptItems.push({ type: 'dept', id: row.orgId, apiFunction: getDept })
            }
            if (row.productId && !seenProduct.has(row.productId)) {
              seenProduct.add(row.productId)
              productItems.push({ type: 'product', id: row.productId, apiFunction: getProduct })
            }
          })
          // 预加载并在完成后强制刷新一次视图
          CacheManager.preloadData([...deptItems, ...productItems]).then(() => {
            this.$nextTick(() => this.$forceUpdate())
          })
        } catch (e) {
          console.warn('预加载关联名称失败：', e)
        }
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.browseId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const browseIds = row.browseId || this.ids
      this.$modal.confirm('是否确认删除用户浏览足迹编号为"' + browseIds + '"的数据项？').then(function() {
        return delHistory(browseIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/browseHistory/export', {
        ...this.queryParams
      }, `history_${new Date().getTime()}.xlsx`)
    },
    // 根据商品ID获取商品名称
    getProductNameById(productId) {
      return CacheManager.getProductName(productId, getProduct)
    },

    // IdSelector需要的方法
    getUser,
    getProduct
  }
}
</script>
